package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.TradeTrademarkCategoryUserRefundBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.function.AsyncDimFunction;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2023/2/23 08:29
 */
public class Dws_11_DwsTradeTrademarkCategoryUserRefundWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_11_DwsTradeTrademarkCategoryUserRefundWindow().init(
            4011,
            2,
            "Dws_11_DwsTradeTrademarkCategoryUserRefundWindow",
            Constant.TOPIC_DWD_TRADE_ORDER_REFUND
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> beanStream = stream
            .map(new MapFunction<String, TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public TradeTrademarkCategoryUserRefundBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    return TradeTrademarkCategoryUserRefundBean.builder()
                        .skuId(obj.getString("sku_id"))
                        .userId(obj.getString("user_id"))
                        .orderIdSet(new HashSet<>(Collections.singleton(obj.getString("order_id"))))
                        .ts(obj.getLong("ts") * 1000)
                        .build();
                }
            });
        // 补充keyBy需要的维度
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> tmIdC3IdStream = AsyncDataStream.unorderedWait(
            beanStream,
            new AsyncDimFunction<TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public String getTable() {
                    return "dim_sku_info";
                }
                
                @Override
                public Object getId(TradeTrademarkCategoryUserRefundBean value) {
                    return value.getSkuId();
                }
                
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean value, JSONObject dim) {
                    value.setCategory3Id(dim.getString("CATEGORY3_ID"));
                    value.setTrademarkId(dim.getString("TM_ID"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
        
        
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> aggregatedStream = tmIdC3IdStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeTrademarkCategoryUserRefundBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            .keyBy(bean -> bean.getCategory3Id() + "_" + bean.getTrademarkId() + "_" + bean.getUserId())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public TradeTrademarkCategoryUserRefundBean reduce(TradeTrademarkCategoryUserRefundBean value1,
                                                                       TradeTrademarkCategoryUserRefundBean value2) throws Exception {
                        value1.getOrderIdSet().addAll(value2.getOrderIdSet());
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradeTrademarkCategoryUserRefundBean, TradeTrademarkCategoryUserRefundBean, String, TimeWindow>() {
                    @Override
                    public void process(String s,
                                        Context ctx,
                                        Iterable<TradeTrademarkCategoryUserRefundBean> elements,
                                        Collector<TradeTrademarkCategoryUserRefundBean> out) throws Exception {
                        TradeTrademarkCategoryUserRefundBean bean = elements.iterator().next();
                        
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                        
                        bean.setRefundCount((long) bean.getOrderIdSet().size());
                        bean.setTs(System.currentTimeMillis());
                        
                        out.collect(bean);
                    }
                }
            );
        
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> tmStream = AsyncDataStream.unorderedWait(
            aggregatedStream,
            new AsyncDimFunction<TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public String getTable() {
                    return "dim_base_trademark";
                }
                
                @Override
                public Object getId(TradeTrademarkCategoryUserRefundBean value) {
                    return value.getTrademarkId();
                }
                
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean value, JSONObject dim) {
                    value.setTrademarkName(dim.getString("TM_NAME"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
        
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> c3Stream = AsyncDataStream.unorderedWait(
            tmStream,
            new AsyncDimFunction<TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category3";
                }
                
                @Override
                public Object getId(TradeTrademarkCategoryUserRefundBean value) {
                    return value.getCategory3Id();
                }
                
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean value, JSONObject dim) {
                    value.setCategory3Name(dim.getString("NAME"));
                    value.setCategory2Id(dim.getString("CATEGORY2_ID"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
        
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> c2Stream = AsyncDataStream.unorderedWait(
            c3Stream,
            new AsyncDimFunction<TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category2";
                }
                
                @Override
                public Object getId(TradeTrademarkCategoryUserRefundBean value) {
                    return value.getCategory2Id();
                }
                
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean value, JSONObject dim) {
                    value.setCategory2Name(dim.getString("NAME"));
                    value.setCategory1Id(dim.getString("CATEGORY1_ID"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> resultStream = AsyncDataStream.unorderedWait(
            c2Stream,
            new AsyncDimFunction<TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category1";
                }
                
                @Override
                public Object getId(TradeTrademarkCategoryUserRefundBean value) {
                    return value.getCategory1Id();
                }
                
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean value, JSONObject dim) {
                    value.setCategory1Name(dim.getString("NAME"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
    
        resultStream.addSink(FlinkSinUtil.getClickHouseSink("dws_trade_trademark_category_user_refund_window", TradeTrademarkCategoryUserRefundBean.class));
        
    }
}
/*
品牌-品类-用户粒度退单各窗口

数据源: 退单表

1. 封装 pojo
    order_id
    
    sku_id
    
2. 由于要分组的维度, 流中的数据不存在, 所以需要先补充维度
3. 分组开窗, 聚合
    品牌 品类
    
 ...
 
 
 
 
 
 

 */